package cn.kinggm520.service;

import cn.kinggm520.domain.Goods;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作者: kinggm Email:731586355@qq.com
 * 时间:  2020-05-23 15:07
 */
@Service
public class GoodsESService {

    @Autowired
    RestHighLevelClient client;



    public void saveGoods(String jsonGoods) throws Exception{

        Goods goods = JSON.parseObject(jsonGoods, Goods.class);

        IndexRequest request=new IndexRequest("goods").id(goods.getId()+"").source(jsonGoods, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        System.out.println("添加成功=================???????????"+response);

    }

/*
    1. 没有输入查询关键字 keyword ,不进行查询
    2. keyword ，使用query String进行查询，从title,brand,category进行查询，操作OR
    3. 添加brand条件   ，filter
    4. 添加价格   最大值最小值   price=1000-2000
     */

    //商品查询
    public List<Goods> findGoods(Map<String,String> param) throws IOException {


        SearchRequest searchRequest = new SearchRequest("goods");

        SearchSourceBuilder sourceBulider = new SearchSourceBuilder();


        //1.构建boolQuery
        BoolQueryBuilder query = QueryBuilders.boolQuery();

        //没有输入查询关键字 keyword ,不进行查询
        if(param==null && StringUtils.isBlank(param.get("keyword"))){
            return new ArrayList<>();
        }
        //keyword ，使用query String进行查询，从title,brand,category进行查询，操作OR
        QueryStringQueryBuilder qsquery = QueryBuilders.queryStringQuery(param.get("keyword"))
                .field("title").field("categoryName").field("brandName")
                .defaultOperator(Operator.OR);
        query.must(qsquery);


        //添加brand条件   ，filter
        if(StringUtils.isNotBlank(param.get("brand"))) {
            QueryBuilder termQuery = QueryBuilders.termQuery("brandName", param.get("brand"));
            query.filter(termQuery);
        }

        //查询价格在：2000-3000
        if(StringUtils.isNotBlank(param.get("price"))) {

            String[] ps = param.get("price").split("-");

            QueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
            ((RangeQueryBuilder) rangeQuery).gte(ps[0]);
            ((RangeQueryBuilder) rangeQuery).lte(ps[1]);
            query.filter(rangeQuery);
        }


        //3.使用boolQuery连接

        sourceBulider.query(query);

        searchRequest.source(sourceBulider);


        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits searchHits = searchResponse.getHits();

        //获取记录数
        long value = searchHits.getTotalHits().value;
        System.out.println("总记录数："+value);


        List<Goods> goodsList = new ArrayList<>();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();

            //转为java
            Goods goods = JSON.parseObject(sourceAsString, Goods.class);

            goodsList.add(goods);
        }
        return goodsList;

    }


}
